<template>
  <a-modal v-model:visible="visible" :title="title" :maskClosable="false" :footer="null">
    <a-form :label-col="labelCol">
      <a-form-item label="菜单类型">
        <a-radio-group v-model:value="formState.type" button-style="solid">
          <a-radio-button value="0">目录</a-radio-button>
          <a-radio-button value="1">菜单</a-radio-button>
          <a-radio-button value="2">按钮</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item v-show="formState.type !== '2'" label="外链菜单">
            <a-radio-group v-model:value="formState.iframe" button-style="solid" size="small">
              <a-radio-button value="true">是</a-radio-button>
              <a-radio-button value="false">否</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item v-show="formState.type !== '2'" label="菜单可见">
            <a-radio-group v-model:value="formState.hidden" button-style="solid" size="small">
              <a-radio-button value="false">是</a-radio-button>
              <a-radio-button value="true">否</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :md="15" :xs="24">
          <a-form-item v-if="formState.type !== '2'" label="菜单标题" v-bind="validateInfos.title">
            <a-input v-model:value="formState.title" placeholder="菜单标题" />
          </a-form-item>
          <a-form-item v-if="formState.type === '2'" label="按钮名称" v-bind="validateInfos.title">
            <a-input v-model:value="formState.title" placeholder="按钮名称" />
          </a-form-item>
        </a-col>
        <a-col :md="9" :xs="24">
          <a-form-item label="排序">
            <a-input-number v-model:value="formState.menuSort" :min="0" :max="999" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item v-show="formState.type === '1' && formState.iframe !== 'true'" label="组件名称">
        <a-input v-model:value="formState.componentName" placeholder="匹配组件内Name字段" />
      </a-form-item>

      <a-form-item v-show="formState.type === '1' && formState.iframe !== 'true'" label="组件路径">
        <a-input v-model:value="formState.component" placeholder="system/user/index" />
      </a-form-item>

      <a-form-item v-if="formState.type !== '2'" label="路由地址" v-bind="validateInfos.path">
        <a-input v-model:value="formState.path" placeholder="user或http(s)://" />
      </a-form-item>

      <a-form-item v-if="formState.type !== '0'" label="权限标识">
        <a-input
          v-model:value="formState.permission"
          :disabled="formState.iframe === 'true'"
          placeholder="user:list"
        />
      </a-form-item>

      <a-form-item label="上级类目">
        <a-tree-select
          v-model:value="formState.pid"
          tree-data-simple-mode
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="categoryOptions"
          placeholder="选择上级类目"
          :load-data="onLoadData"
          :field-names="replaceFields"
        />
      </a-form-item>
      <a-form-item style="margin-bottom: 0px; margin-top: 40px; text-align: right">
        <a-button type="primary" @click.prevent="onSubmit">确认</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
  import { defineComponent, toRaw, reactive, ref, watch } from 'vue';
  import { Form, notification } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { getMenuSuperiorApi, getMenusLazyApi, addMenuApi, editMenuApi } from '/@/api/menu';
  import { reload } from './index';

  const replaceFields = {
    children: 'children',
    title: 'name',
    value: 'id',
    isLeaf: 'leaf',
  };

  const formState = reactive({
    id: null,
    type: '0',
    pid: 0,
    menuSort: 999,
    title: '',
    iframe: 'false',
    hidden: 'false',
    componentName: '',
    component: '',
    path: '',
    permission: '',
    icon: '',
    cache: false,
  });
  const rulesRef = reactive({
    title: [
      {
        required: true,
        message: '请输入标题',
      },
    ],
    path: [
      {
        required: true,
        message: '请输入地址',
      },
    ],
  });
  const useForm = Form.useForm;
  const { resetFields, validate, validateInfos } = useForm(formState, rulesRef);
  const userStore = useUserStore();

  export default defineComponent({
    setup() {
      const visible = ref<boolean>(false);
      const title = ref<string>('');
      watch(visible, (newVal, _oldVal) => {
        if (!newVal) {
          resetFields();
        }
      });

      const categoryOptions = ref<any>([]);
      const getCategorys = async (id: number) => {
        const res = await getMenuSuperiorApi([id]);
        const children = res?.map(function (obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null;
          }
          return obj;
        });
        categoryOptions.value = [{ id: 0, label: '顶级类目', children: children }];
      };

      const open = async (isAdd: boolean, record) => {
        if (isAdd) {
          title.value = '新增菜单';
          categoryOptions.value.push({ id: 0, label: '顶级类目', children: null });
        } else {
          title.value = '编辑菜单';
          formState.type = String(record.type);
          formState.id = record.id;
          formState.pid = record?.pid || 0;
          formState.title = record.title;
          formState.iframe = String(record.iFrame);
          formState.hidden = String(record.hidden);
          formState.componentName = record.componentName;
          formState.component = record.component;
          formState.path = record.path;
          formState.permission = record.permission;
          formState.menuSort = record.menuSort;
          formState.icon = record.icon;
          getCategorys(record.id);
        }
        visible.value = true;
      };

      const onLoadData = (treeNode: any) => {
        return new Promise((resolve: (value?: unknown) => void) => {
          if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
            resolve();
            return;
          }
          setTimeout(async () => {
            const id = treeNode.dataRef.id;
            const data = categoryOptions.value;
            let response = await getMenusLazyApi({
              pid: id,
            });
            //获取到的子节点
            const children = response ?? [];
            const dataMap = (items: Array<any>) => {
              items.find((item) => {
                if (item.id === id) {
                  //找到当前要展开的节点
                  item.children = children;
                  return items;
                }
                if (item.children && item.children.length > 0) {
                  dataMap(item.children);
                }
              });
            };
            dataMap(data || []);
            categoryOptions.value = data;
            resolve(true);
          }, 200);
        });
      };

      const onSubmit = (_e: MouseEvent) => {
        validate()
          .then(async () => {
            const item = toRaw(formState);
            try {
              if (!!formState.id) {
                await editMenuApi({
                  ...item,
                  type: Number(item.type),
                  hidden: item.hidden === 'true',
                  iFrame: item.iframe === 'true',
                });
                notification['success']({
                  message: '编辑菜单成功',
                  duration: 3,
                });
              } else {
                await addMenuApi({
                  ...item,
                  type: Number(item.type),
                  hidden: item.hidden === 'true',
                  iFrame: item.iframe === 'true',
                });
                notification['success']({
                  message: '新增菜单成功',
                  duration: 3,
                });
              }
              visible.value = false;
              reload.value = !reload.value;
            } catch (error) {}
          })
          .catch((err) => {
            console.log('error', err);
          });
      };

      const user = userStore.getUser;

      return {
        user,
        open,
        visible,
        title,
        onSubmit,
        labelCol: { style: { width: '80px' } },
        wrapperCol: { span: 14 },
        validateInfos,
        resetFields,
        formState,
        categoryOptions,
        onLoadData,
        replaceFields,
      };
    },
  });
</script>
